package com.lg.my.netty.reconnect;

import com.lg.consts.NettyConst;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.concurrent.TimeUnit;

/**
 * @author by Mr. Li 2021/4/22 22:44
 */
public class ReConnectNettyClient {
    private String address_ip;
    private int port;
    private EventLoopGroup group;
    private Bootstrap bootstrap;

    public static void main(String[] args) throws InterruptedException {
        final ReConnectNettyClient reConnectNettyClient = new ReConnectNettyClient(NettyConst.ADDRESS_IP, NettyConst.ADDRESS_PORT);
        reConnectNettyClient.connect();
    }

    public ReConnectNettyClient(String address_ip, int port) {
        this.address_ip = address_ip;
        this.port = port;
        this.init();
    }

    private void init() {
        group = new NioEventLoopGroup();

        try {
            bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            //加入处理器
                            ch.pipeline().addLast(new ReConnentNettyClientHandler(ReConnectNettyClient.this));
                        }
                    });

        } finally {
            group.shutdownGracefully();
        }

    }

    public void connect() throws InterruptedException {
        // 启动服务器
        System.out.println("netty client start...");
        final ChannelFuture channelFuture = bootstrap.bind(address_ip, port);
        // 添加一个监听器
        channelFuture.addListener((ChannelFutureListener) future -> {
            if (!future.isSuccess()) {
                // 交给线程池运行
                future.channel().eventLoop().schedule(() -> {
                    System.err.println("client is up, retry connect....");
                    try {
                        connect();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }, 3000, TimeUnit.MILLISECONDS);
            } else {
                System.out.println("client connection succeeded...");
            }
        });
        channelFuture.channel().closeFuture().sync();
    }
}
